﻿using Newtonsoft.Json;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinFormium;
using WinFormium.JavaScript;

namespace MiMiPcNetFrameWork
{
    internal class JSBing : JavaScriptWindowBindingObject
    {

        public override string Name => "Tmm";
        public override string JavaScriptWindowBindingCode =>
@"
var Tmm = {
     test: function(message){
         native function Alert();
         return Alert(message);
     },
     testAsync: function(message, num){
         native function AlertAsync();
         return AlertAsync(message,num);
     },
     Exit: function(message){
         native function Exit();
         return Exit();
     },
};
";
        public JSBing()
        {
            RegisterSynchronousNativeFunction(Alert);
            RegisterSynchronousNativeFunction(Exit);
            RegisterAsynchronousNativeFunction(AlertAsync);
        }
        public JavaScriptValue Exit(Formium sender, JavaScriptArray arguments)
        {
            Application.Exit();
            return null;
        }
        public JavaScriptValue Alert(Formium sender, JavaScriptArray arguments)
        {
            var stringArg = arguments.FirstOrDefault(x => x.ValueType == JavaScriptValueType.String)?.GetString() ?? string.Empty;
            MessageBox.Show(sender, $"前端调用传参:{stringArg}");
            return null;
        }

        public async void AlertAsync(Formium sender, JavaScriptArray arguments, JavaScriptPromise promise)
        {
            var stringArg = arguments.FirstOrDefault(x => x.ValueType == JavaScriptValueType.String)?.GetString() ?? string.Empty;
            var intArg = arguments.FirstOrDefault(x => x.ValueType == JavaScriptValueType.Number)?.GetInt() ?? 0;
            var rnd = new Random(DateTime.Now.Millisecond);
            var delayed = rnd.Next(1, 1000);
            await Task.Delay(delayed);
            promise.Resolve($"Hello from C# with value:{intArg} and delayed:{delayed}ms.");
        }
    }
}
